package _0_composite

import "fmt"

//Component 组件 抽象成接口
type Component interface {
	Name(name string)
	GetName() string
	Parent(Component)
	GetParent() Component
	AddChild(Component)
	Print()
}

//component 与开放接口组合形成抽象实现
type component struct {
	name   string
	parent Component
}

func (c *component) Name(name string) {
	c.name = name
}

func (c *component) GetName() string {
	return c.name
}

func (c *component) Parent(component Component) {
	c.parent = component
}

func (c *component) GetParent() Component {
	return c.parent
}

func (c *component) AddChild(Component) {

}

func (c *component) Print() {

}

// Composite 复合节点 实现component未实现的部分
type Composite struct {
	component
	childs []Component
}

func (c *Composite) AddChild(child Component) {
	child.Parent(c)
	c.childs = append(c.childs, child)
}

func (c *Composite) Print() {
	pre := ""
	fmt.Printf("%s+%s\n", pre, c.GetName())
	pre += " "
	for _, comp := range c.childs {
		comp.Print()
	}
}

// Leaf 叶子节点
type Leaf struct {
	component
}

func (c *Leaf) AddChild(child Component) {
	panic("leaf is not support AddChild")
}

func (c *Leaf) Print() {
	pre := ""
	fmt.Printf("%s+%s\n", pre, c.GetName())
}
